//
//  Account.swift
//  TODOApp
//
//  Created by chenyh on 2018/5/30.
//  Copyright © 2018年 chenyh. All rights reserved.
//

import Foundation
import HandyJSON
public protocol Archivable {
    func archive() -> [String: Any]
    init?(unarchive: [String: Any]?)
}
struct Account: HandyJSON {
    var username: String = ""
    var uid: String = ""
    var token: String = ""
    var last_login: String = ""
    var expiredTime: String = ""
}
extension Account: Decodable {
    
    static func parse(any: Any) -> Account? {
        guard  let values =  any as? [String: Any] else {return nil}
        return Account.deserialize(from: values)
    }
}
extension Account {
    
    private static var archivePath: String {
        get {
            return "\(NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!)/todo.data"
        }
    }
    static func unarchiveObject() -> Account? {
        return unarchiveObjectWithFile(path: Account.archivePath)
    }
    
    func archiveObject() {
        TODOApp.archiveObject(object: self, toFile: Account.archivePath)
    }
    
    static func logout() {
        if FileManager.default.fileExists(atPath: archivePath)
        {
            try? FileManager.default.removeItem(atPath: archivePath)
        }
    }
}

extension Account: Archivable {
    
    func archive() -> [String: Any] {
        
        var archiveDic = [String: Any]()
            archiveDic.updateValue(username, forKey: "username")
            archiveDic.updateValue(uid, forKey: "uid")
            archiveDic.updateValue(token, forKey: "token")
            archiveDic.updateValue(last_login, forKey: "last_login")
            archiveDic.updateValue(expiredTime, forKey: "expiredTime")
        return archiveDic
    }
    
    init?(unarchive: [String: Any]?) {
        guard let values = unarchive else {
            return nil
        }
        self.last_login = values["last_login"] as! String
        self.expiredTime = values["expiredTime"] as! String
        self.username = values["username"] as! String
        self.uid = values["uid"] as! String
        self.token = values["token"] as! String
       
    }
}

public func unarchiveObjectWithFile<T: Archivable>(path: String) -> T? {
    return T(unarchive: NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [String: Any])
}

public func archiveObject<T: Archivable>(object: T, toFile path: String) {
    if NSKeyedArchiver.archiveRootObject(object.archive(), toFile: path) {
        printLog("本地缓存成功!")
    }
}
